import 'package:flutter/material.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:dio/dio.dart';
import 'package:flutter_juwo/provider/UserModel.dart';
import 'package:flutter_juwo/ui/controller/MyPageState.dart';
import 'package:flutter_juwo/ui/controller/NetUtils.dart';
import 'package:flutter_juwo/ui/custom/NotLoginPage.dart';
import 'package:flutter_juwo/ui/custom/noData.dart';
import 'package:flutter_juwo/ui/res/shared_preferences_keys.dart';
import 'package:flutter_juwo/ui/utils/sp_util.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';

import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/ball_pulse_header.dart';
import 'package:flutter_easyrefresh/ball_pulse_footer.dart';
import 'package:provider/provider.dart';

import 'model/list_entity.dart';

class RepresentationList extends StatefulWidget {
  @override
  _RepresentationListState createState() => _RepresentationListState();
}

class _RepresentationListState extends State<RepresentationList>
    with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  ListEntity _listEntity = null;
  MyPageState ps = MyPageState.LOADING;

  EasyRefreshController _easyRefreshController = EasyRefreshController();

  ///当前码
  int _currentPage = 1;

  ///页数默认为1 通过 总数 计算得来
  int _pages = 1;

  ///一页 20 条数据
  int _itemNum = 20;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.init();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: UiUtils.appBar(context, "我的申诉"),
      body: Column(
        children: <Widget>[
          UiUtils.divider(),
          Expanded(
            flex: 1,
            child: Consumer<UserModel>(
              builder: (context, UserModel userModel, _) {
                return getContent(userModel);
              },
            ),
          )
        ],
      ),
      floatingActionButton: GestureDetector(
        onTap: () {
          NavigatorUtils.pushResult(
              context, Routes.addRepresentation, (result) {
                if(result){
                  //
                  _easyRefreshController.callRefresh();
                }
          });
        },
        child: Container(
          margin: EdgeInsets.only(bottom: ScreenUtil().setWidth(30)),
          alignment: Alignment.center,
          height: ScreenUtil().setWidth(60),
          width: ScreenUtil().setWidth(180),
          decoration: BoxDecoration(
              color: Colours.appC16, borderRadius: BorderRadius.circular(16)),
          child: Text(
            "我要申诉",
            style: TextStyles.custom(
                30, Colors.white, Font.PingFangMedium),
          ),
        ),
      ),
    );
  }

  getContent(UserModel userModel) {
    if (SpUtil.getString(SpKeys.userToken).isEmpty) {
      ps = MyPageState.NOT_LOGIN;
    }
    if (userModel.value.isNotEmpty) {
      ps = MyPageState.HAVE_DATA;
    }

    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }
    if (ps == MyPageState.NOT_LOGIN) {
      return NotLoginPage();
    }

    if (ps == MyPageState.NOT_DATA) {
      return NoData(this.getData);
    }

    if (ps == MyPageState.HAVE_DATA) {
      if (null == _listEntity) {
        init();
        return LoadingPage();
      }
      return EasyRefresh.custom(
        controller: _easyRefreshController,

        /// firstRefresh: true,
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        header: BallPulseHeader(),
        footer: BallPulseFooter(),
        onRefresh: () async {
          await Future.delayed(Duration(seconds: 1), () {
            _currentPage = 1;
            this.getData(page: _currentPage);
          });
        },
        onLoad: () async {
          await Future.delayed(Duration(seconds: 1), () {
            if (_currentPage < _pages) {
              _currentPage++;
              this.getData(page: _currentPage);
            } else {
              _easyRefreshController.finishLoad();
              ToastUtil.showShortToast("没有更多了");
            }
          });
        },
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return this.getItem(_listEntity.data.value[index]);
              },
              childCount: _listEntity.data.value.length,
            ),
          ),
        ],
      );
    }

    return NoData(this.getData);
  }

  Future getData({int page = 1}) async {
    FormData formData = FormData.from({"page": page, "size": "$_itemNum"});
    DioManager.getInstance().get(Api.USER_APPLY, formData, (json) {
      print("获取申诉列表数据SUC：${json}");
      ListEntity data = ListEntity.fromJson(json);
      if (data.code == Api.SUCCESS_CODE) {
        ///1.判断有没有获取到数据
        if (null == data.data.value || data.data.value.length <= 0) {
          this.noData();
          return;
        }

        ///获取页数
        int all = data.data.totalPage;
        _pages = (all / _itemNum).ceil();
        print("页数：$_pages");

        ///2.判断本来有没有数据
        if (null == _listEntity) {
          _listEntity = data;
          this.haveData();
          return;
        }

        ///3.下拉刷新数据
        if (page == 1) {
          _currentPage = 1;
          _listEntity.data.value.clear();
          _listEntity = data;
          this.haveData();
          _easyRefreshController.finishRefresh(success: true);
          return;
        }

        ///4.上拉加载
        _listEntity.data.value.addAll(data.data.value);
        this.haveData();
        _easyRefreshController.finishLoad(
            success: true, noMore: _pages == _currentPage);
        return;
      }

      if (_listEntity.code == Api.ERROR_CODE_0 ||
          _listEntity.code == Api.ERROR_CODE) {
        ToastUtil.showShortErrToast(_listEntity.message);
        return;
      }
    }, (errMsg) {
      print("申诉列表数据ERR：${errMsg}");
    });
  }

  ///没有数据
  void noData() {
    ps = MyPageState.NOT_DATA;
    setState(() {});
  }

  ///有数据
  void haveData() {
    ps = MyPageState.HAVE_DATA;
    setState(() {});
  }

  getItem(ListDataValue value) {
    return Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[
          GestureDetector(
            onTap: () {
              ///跳转到详情页面
              NavigatorUtils.push(context, "${Routes.representationDetails}?id=${value.id}");
            },
            child: Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(
                      left: ScreenUtil().setWidth(30),
                      top: ScreenUtil().setWidth(20),
                      bottom: ScreenUtil().setWidth(20),
                      right: ScreenUtil().setWidth(15)),
                  child: Text(
                    "${value.status == "0" ? "待回复" : "已回复"}",
                    style: TextStyles.custom(
                        32,
                        value.status == "0" ? Colours.appC11 : Colors.green,
                        Font.PingFangMedium),
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Container(
                    child: Text("${value.problemName}",
                        style: TextStyles.custom(
                            32, Colours.appC2, Font.PingFangMedium)),
                  ),
                ),
                Container(
                  margin:
                      EdgeInsets.fromLTRB(0, 0, ScreenUtil().setWidth(30), 0),
                  child: Text("${value.createdAt}",
                      style: TextStyles.custom(
                          32, Colours.appC3, Font.PingFangMedium)),
                ),
              ],
            ),
          ),
          UiUtils.divider()
        ],
      ),
    );
  }

  void init() {
    bool isLogin = NetUtils.isLogin();
    if (isLogin) {
      ///获取数据
      this.getData();
    } else {
      ps = MyPageState.NOT_LOGIN;
    }
  }
}
